package top.moyel.hmi4k.mapstruct

import cn.hutool.json.JSONUtil
import top.moyel.hmi4k.entity.HmiDetail
import top.moyel.hmi4k.entity.HmiDetailReal
import top.moyel.hmi4k.entity.HmiRemark
import java.util.Objects

object HmiDetailMapStruct {
    private const val SPLITERATOR = ","

    /**
     * 解析组字符串
     *
     * @param groups 组字符串
     * @return 组列表
     */
    private fun parseGroups(groups: String?): List<String>? {
        return groups?.split(SPLITERATOR)?.toList()
    }

    /**
     * 解析其他信息字符串
     *
     * @param extraInfo 其他信息字符串
     * @return 其他信息
     */
    private fun parseExtraInfo(extraInfo: String?): Any? {
        if (Objects.isNull(extraInfo)) {
            return null
        }

        if (!JSONUtil.isTypeJSON(extraInfo!!)) {
            return extraInfo
        }

        return JSONUtil.parse(extraInfo)
    }

    /**
     * 转换成HmiDetailReal
     *
     * @param hmiDetail HmiDetail
     * @return HmiDetailReal
     */
    fun toReal(hmiDetail: HmiDetail): HmiDetailReal {
        return HmiDetailReal(
            hmiCode = hmiDetail.hmiCode,
            groups = parseGroups(hmiDetail.groups),
            param = hmiDetail.param,
            paramName = hmiDetail.paramName,
            matrix = hmiDetail.matrix,
            expression = hmiDetail.expression,
            mappingValue = hmiDetail.mappingValue,
            defaultValue = hmiDetail.defaultValue,
            unit = hmiDetail.unit,
            remark = HmiRemark.of(hmiDetail.remark),
            extraInfo = parseExtraInfo(hmiDetail.extraInfo)
        )
    }
}